<?

class Mojito_Db_Table_Row_Abstract extends Zend_Db_Table_Row_Abstract
{
	/**
	 * _columnMap
	 * maps psudo name => real db column name
	 * (default value: array())
	 * 
	 * @var array
	 * @access protected
	 */
	protected $_columnMap=array();
	
	/**
	 * used to store columns=>values from other tables
	 * 
	 * @var mixed
	 * @access protected
	 */
	protected $_extra=array();
	
	/**
	 * extracts columns not belonging to this table into $this->_extra, leaving $this->_data pure
	 * 
	 * @access public
	 * @return void
	 */
	protected function extra()
	{
		$info=$this->getTable()->info();
		$this->_extra=array_diff_key($this->_data,array_flip($info['cols']));
		$this->_data=array_diff_key($this->_data,$this->_extra);
	}
	
	/**
	 * looks for values in $this->_extra
	 * 
	 * @access public
	 * @param mixed $columnName
	 * @return void
	 */
	public function __get($columnName)
	{
		if (array_key_exists($columnName, $this->_extra)) return $this->_extra[$columnName];
		else return parent::__get($columnName);
	}

	/**
	 * populate function.
	 * 
	 * @access public
	 * @param mixed Zend_Form $Form
	 * @return void
	 */
	public function populate(Zend_Form $Form)
	{
		$values = array();
		if (!empty($this->_columnMap)) foreach ($this->_columnMap as $form_input=>$db_field) $values[$form_input]=$this->{$db_field};
		else $values=$this->toArray();
		$Form->populate($values);
	}
	
	
    public function setFromArray(array $data)
    {
    	// the following line in parent::setFromArray() ends up skipping _transformColumn, 
    	// thereby thwarting attempts at column name mapping in conjunction with this function 
    	// (my apologies, I did not mean to rhyme)
        
        // $data = array_intersect_key($data, $this->_data);

        foreach ($data as $columnName => $value) {
            $this->__set($columnName, stripslashes($value));
        }

        return $this;
    }
    
    public function toArray()
    {
        return array_merge($this->_data,$this->_extra);
    }

    
    /**
     * __set function.
     * prevent primary from being set if it is already
     * useful for prevent hacks through $_POST or $_GET
     * @access public
     * @param mixed $columnName
     * @param mixed $value
     * @return void
     */
    public function __set($columnName, $value)
	{
		if ($columnName==$this->_primary[1])
		{
			if (!empty($this->{$this->_primary[1]})) return;
		}
		parent::__set($columnName, $value);
	}	
	
	/**
	 * _transformColumn function.
	 * provides ability to perform column name maping using $this->_columnMap
	 * @access protected
	 * @param mixed $columnName
	 * @return void
	 */
	protected function _transformColumn($columnName)
	{
		if (array_key_exists($columnName,$this->_columnMap)) $columnName=$this->_columnMap[$columnName];
		return parent::_transformColumn($columnName);
	}

}